package com.mmall.controller.backstage;

import com.google.common.collect.Maps;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.Product;
import com.mmall.service.IFileService;
import com.mmall.service.IProductService;
import com.mmall.service.IUserService;
import com.mmall.util.PropertiesUtil;
import com.mmall.vo.ProductDetailVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 后台商品管理控制层
 * Created by qezhhnjy on 2017/9/27-20:42.
 */
@Controller
@RequestMapping("/manage/product/")
public class ProductManageController {

    @Resource
    private IUserService iUserService;

    @Resource
    private IProductService iProductService;

    @Resource
    private IFileService iFileService;

    /**
     * 插入或更新商品信息
     *
     * @param session 当前会话
     * @param product 前端封装的商品对象
     * @return 响应对象
     */
    @ResponseBody
    @RequestMapping(value = "save.do", method = RequestMethod.POST)
    public ServerResponse productSave(HttpSession session, Product product) {
        ServerResponse response = iUserService.adminCheck(session);
        if (response.isSuccess())
            return iProductService.productSave(product);
        return response;
    }

    /**
     * 修改指定id 商品的销售状态
     *
     * @param session   当前会话
     * @param productId 指定商品id
     * @param status    需要修改后的状态
     * @return 响应对象
     */
    @ResponseBody
    @RequestMapping(value = "set_sale_status.do", method = RequestMethod.POST)
    public ServerResponse setSaleStatus(HttpSession session, Integer productId, Integer status) {
        ServerResponse response = iUserService.adminCheck(session);
        if (response.isSuccess())
            return iProductService.setSaleStatus(productId, status);
        return response;
    }

    /**
     * 这里为了配合前端页面显示测试, 对返回类型进行了修改.因为不会前端解析json对象.
     * 获取指定id 商品的详细信息
     *
     * @param session   当前会话
     * @param productId 商品id
     * @return 响应对象
     */
    @RequestMapping(value = "get_detail.do", method = RequestMethod.POST)
    public String getDetail(HttpSession session, Integer productId, Model model) {
        ServerResponse response = iUserService.adminCheck(session);
        if (response.isSuccess()) {
            ServerResponse<ProductDetailVo> sr = iProductService.manageProductDetail(productId);
            model.addAttribute("product", sr.getData());
            return "product";
        }
        return "product";
    }

    @RequestMapping(value = "update_get_detail.do", method = RequestMethod.POST)
    public String updateGetDetail(HttpSession session, Integer productId, Model model) {
        ServerResponse response = iUserService.adminCheck(session);
        if (response.isSuccess()) {
            ServerResponse<ProductDetailVo> sr = iProductService.manageProductDetail(productId);
            model.addAttribute("product", sr.getData());
            return "manager";
        }
        return "manager";
    }

    /**
     * 简单实现查询分页功能
     *
     * @param session  当前会话
     * @param pageNum  当前页码
     * @param pageSize 每页数量
     * @return 响应对象
     */
    @ResponseBody
    @RequestMapping(value = "list.do", method = RequestMethod.POST)
    public ServerResponse getList(HttpSession session, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        ServerResponse response = iUserService.adminCheck(session);
        if (response.isSuccess())
            return iProductService.getList(pageNum, pageSize);
        return response;
    }

    /**
     * 后台商品搜索功能开发
     *
     * @param session     当前会话
     * @param productName 商品名称,支持模糊查询
     * @param productId   指定商品id
     * @param pageNum     当前页码
     * @param pageSize    每页数量
     * @return 响应对象
     */
    @ResponseBody
    @RequestMapping(value = "search.do", method = RequestMethod.POST)
    public ServerResponse Search(HttpSession session, String productName, Integer productId, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        ServerResponse response = iUserService.adminCheck(session);
        if (response.isSuccess())
            return iProductService.search(productName, productId, pageNum, pageSize);
        return response;
    }

    /**
     * 配合前端页面file.jsp 实现文件上传并预览
     *
     * @param file    包装文件信息对象
     * @param request 请求
     * @return 视图页面
     */
//    @ResponseBody
    @RequestMapping(value = "upload.do", method = RequestMethod.POST)
    public String upload(MultipartFile file, HttpServletRequest request) {
        String path = request.getSession().getServletContext().getRealPath("upload");
        request.setAttribute("file", iFileService.upload(file, path));
        return "file";
    }

    /**
     * 后端文件上传到FTP 服务器并返回上传后的文件地址
     *
     * @param file    包装文件信息对象
     * @param request 请求
     * @return 响应对象
     */
    @ResponseBody
    @RequestMapping(value = "upload2.do", method = RequestMethod.POST)
    public ServerResponse upload2(MultipartFile file, HttpServletRequest request) {
        String path = request.getSession().getServletContext().getRealPath("upload");
        ServerResponse response = iUserService.adminCheck(request.getSession());
        Map<String, String> fileMap = Maps.newHashMap();
        if (response.isSuccess()) {
            String targetFileName = iFileService.upload(file, path);
            if (StringUtils.isBlank(targetFileName)) return ServerResponse.createByErrorMessage("图片上传到FTP服务器失败~!");
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;
            fileMap.put("uri", targetFileName);
            fileMap.put("url", url);
            return ServerResponse.createBySuccess(fileMap);
        }
        return response;
    }

    /**
     * 通过富文本simditor进行图片上传.
     *
     * @param file    图片上传后包装的图片数据对象
     * @param request Web 请求
     * @param resp    Web 响应
     * @return 按照simditor包装的Map对象
     */
    @ResponseBody
    @RequestMapping(value = "rich_text_upload.do", method = RequestMethod.POST)
    public Map richtextImgUpload(MultipartFile file, HttpServletRequest request, HttpServletResponse resp) {
        ServerResponse response = iUserService.adminCheck(request.getSession());
        String msg = response.getMsg();
        Map<String, Object> resultMap = Maps.newHashMap();
        //富文本中对于返回值有自己的要求,我们使用simditor,所以按照simditor的要求进行返回
        //{
        //    "success": true/false,
        //    "msg": "error message", # optional
        //    "file_path": "[real file path]"
        //}
        //同时在上传成功后要对response的header进行配置
        if (response.isSuccess()) {
            String path = request.getSession().getServletContext().getRealPath("upload");
            String targetFileName = iFileService.upload(file, path);
            if (StringUtils.isBlank(targetFileName)) {
                resultMap.put("success", false);
                resultMap.put("msg", "上传失败");
                return resultMap;
            }
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;
            resultMap.put("success", true);
            resultMap.put("msg", "上传成功");
            resultMap.put("file_path", url);
            //配置响应的header
            resp.addHeader("Access-Control-Allow-Headers", "X-File-Name");
            return resultMap;
        }
        resultMap.put("success", false);
        resultMap.put("msg", msg);
        return resultMap;
    }
}